package py.com.alfa.escriba.gui.controller;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.WebApplicationContext;
import org.thymeleaf.TemplateEngine;
import org.winter.dialect.response.JsonResponse;
import org.winter.utils.command.AjaxResponse;
import org.winter.utils.command.ControllerObject;

import py.com.alfa.escriba.gui.controller.object.admin.ClientesControllerObject;
import py.com.alfa.escriba.gui.controller.view.View;
import py.com.alfa.escriba.gui.controller.view.ViewManager;
import py.com.alfa.escriba.gui.dto.GenericDTO;
import py.com.alfa.escriba.gui.dto.admin.ClienteDTO;
import py.com.alfa.escriba.gui.dto.admin.ClienteInfoDTO;
import py.com.alfa.escriba.gui.dto.admin.DomicilioDTO;
import py.com.alfa.escriba.gui.dto.admin.TelefonoDTO;
import py.com.alfa.escriba.gui.rest.services.AdminService;
import py.com.alfa.escriba.gui.services.HelperService;
import py.com.alfa.escriba.gui.session.SystemInfo;
import py.com.alfa.escriba.gui.spring.processors.SpringBean;
import py.com.sif.rest.client.spring.exception.RestClientException;

@Controller
@Scope("session")
@SessionAttributes("clientes")
@RequestMapping("/clientes")
public class ClientesController implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3807025844096914070L;
	private final static String PAGE_NAME = "pag:clientes";
	private final static String CONTROLLER_OBJECT_NAME = "clientes";
	
	private Logger log = LoggerFactory.getLogger(getClass());
	@SpringBean private SystemInfo systemInfo;
	@SpringBean private ViewManager viewManager;
	@SpringBean private AdminService adminService;
	@SpringBean private HelperService helperService;
//	@SpringBean private List<GenericDTO> generoList;
	@SpringBean private List<GenericDTO> paisesList;
//	@SpringBean private List<GenericDTO> estadoCivilList;
	
	@Autowired
	private WebApplicationContext wac;
	
	@Autowired
	private TemplateEngine templateEngine;
	@ControllerObject	
	private ClientesControllerObject clientes;
	private Locale locale;
	
	
	public ClientesController() {
		this.loadObjects();
	}

	private void loadObjects() {
		setLocale(LocaleContextHolder.getLocale());
	}

	private String verifAuto() {
		Subject subject = SecurityUtils.getSubject();
		if (subject == null || !subject.isAuthenticated()) {
			return "redirect:/";
		}		
		Boolean permitted = subject.isPermitted(ClientesController.PAGE_NAME);
		systemInfo.setSystemError(false);
		if (!permitted) {
			systemInfo.setSystemError(true);
			systemInfo.setErrorMessage("El usuario no esta autorizado para utilizar este recurso");
			return "error";
		}
		return null;
	}

	
	@ModelAttribute(CONTROLLER_OBJECT_NAME)
	public ClientesControllerObject getClientes() {
		return this.clientes;
	}

	public void setClientes(ClientesControllerObject listas) {
		this.clientes = listas;
	}

	public Locale getLocale() {
		return locale;
	}

	public void setLocale(Locale locale) {
		this.locale = locale;
	}
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String homePage(Model model, HttpServletRequest request, HttpServletResponse response) {
		this.log.info("clientes!");
		try {
			this.getClientes().view().disableAll();
			String auto = this.verifAuto();
			if ( auto != null ) {
				return auto;
			}
			this.getClientes().setClientes(this.adminService.obtenerClientes());
			this.getClientes().view().enable().lista();
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
		}
		return View.CLIENTES;
	}

	@RequestMapping(value = "/agregarCliente", method = RequestMethod.POST)
	public @ResponseBody JsonResponse agregarCliente(Model model, HttpServletRequest request, HttpServletResponse response, 
		@AjaxResponse(View.CLIENTES) JsonResponse jResponse) {
		this.log.info("clientes - Nuevo!");
		this.getClientes().setCliente(new ClienteInfoDTO());
		this.getClientes().getCliente().setActivo(true);
		
		try {
			this.getClientes().setEstadosCiviles(this.helperService.getTablaRef("ESTCIV"));
			this.getClientes().setEstadoCivil(this.getClientes().getEstadosCiviles().get(0));
			this.getClientes().setGeneros(this.helperService.getTablaRef("GENERO"));
			this.getClientes().setSexo(this.getClientes().getGeneros().get(0));
			
			if(CollectionUtils.isNotEmpty(paisesList)){
				this.getClientes().setPais(paisesList.get(0));
				this.getClientes().setPaises(paisesList);
			}
			
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
			return jResponse.error(e.getMessage());
		}
		
		this.getClientes().view().disableAll().enable().cliente();

		return jResponse.success(request, response, wac, model, templateEngine);
	}	

	
	@RequestMapping(value = "/cancelar/{operacion}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse cancelar(Model model, HttpServletRequest request, HttpServletResponse response, 
		@AjaxResponse(View.CLIENTE) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ClientesControllerObject clientes, BindingResult bindingResult, 
		@PathVariable("operacion") String operacion) {
		this.log.info("clientes - cancelar! {}", operacion);
		try {
			if ( operacion == null ) {
				return jResponse.error("Debe informar la operacion a cancelar");
			}
			if ( "DOMICILIO".equals(operacion)) {
				if ( this.getClientes().getDomicilioOri() != null) {
					this.getClientes().getCliente().getDomicilios().add(this.getClientes().getDomicilioOri());
				}
				this.getClientes().setDomicilioOri(null);
			    this.getClientes().setDomicilio(null);
			    this.getClientes().view().disableAll().enable().cliente();
			} else	if ( "TELEFONO".equals(operacion)) {
				if ( this.getClientes().getTelefonoOri() != null) {
					this.getClientes().getCliente().getTelefonos().add(this.getClientes().getTelefonoOri());
				}
				this.getClientes().setTelefonoOri(null);
			    this.getClientes().setTelefono(null);
			    this.getClientes().view().disableAll().enable().cliente();
			} else if ( "CLIENTES".equals(operacion)) {
			    this.getClientes().setDomicilio(null);
			    this.getClientes().setTelefono(null);
			    this.getClientes().setSexo(null);
			    this.getClientes().setEstadoCivil(null);
			    this.getClientes().setPais(null);
			    this.getClientes().setCliente(null);
			    this.getClientes().view().disableAll().enable().lista();
			    jResponse.setView(View.CLIENTES);
			}			
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}	
	
	
	@RequestMapping(value = "/addDireccion", method = RequestMethod.POST)
	public @ResponseBody JsonResponse addDireccion(Model model, HttpServletRequest request, HttpServletResponse response, 
		@AjaxResponse(View.CLIENTE) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ClientesControllerObject clientes, BindingResult bindingResult) {
		this.log.info("clientes - addDireccion!");
		try {
		    this.getClientes().setDomicilio(null);
		    this.getClientes().setDomicilioOri(null);
			this.getClientes().setTipos(this.helperService.getTablaRef("TIPDOM"));
			this.getClientes().setDepartamentos(this.helperService.getDepartamentos());
//			this.getClientes().setBarrios(null);
			this.getClientes().setDistritos(null);
			if ( this.getClientes().getDepartamentos() != null && !this.getClientes().getDepartamentos().isEmpty()) {
			  this.getClientes().setDistritos(this.helperService.getDistritos(this.getClientes().getDepartamentos().get(0).getId()));	
			}
//			if ( this.getClientes().getDistritos() != null && !this.getClientes().getDistritos().isEmpty()) {
//				  this.getClientes().setBarrios(this.helperService.getBarrios(this.getClientes().getDistritos().get(0).getId()));					
//			}
			this.getClientes().view().enable().domicilio();
		} catch (IOException e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}

		return jResponse.success(request, response, wac, model, templateEngine);
	}	
	
	@RequestMapping(value = "/departamentoEvent", method = RequestMethod.POST)
	public @ResponseBody JsonResponse departamentoEvent(Model model, HttpServletRequest request, HttpServletResponse response, 
	       @AjaxResponse(View.CLIENTE) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ClientesControllerObject clientes, BindingResult bindingResult) {
		
		this.log.info("INDICADOR DEPARTAMENTO EVENT! {}", this.getClientes().getDomicilio().getDepartamento());
		try {
			this.getClientes().setDistritos(null);
			this.getClientes().setBarrios(null);
			if ( this.getClientes().getDomicilio().getDepartamento() != null) {
				  Long id = this.getClientes().getDomicilio().getDepartamento().getId();
				  this.getClientes().getDomicilio().setDepartamento(this.helperService.getDepartamentoById(id));
				  this.getClientes().setDistritos(this.helperService.getDistritos(id));				
		    }
			if ( this.getClientes().getDistritos() != null  && !this.getClientes().getDistritos().isEmpty()) {
				  this.getClientes().setBarrios(this.helperService.getBarrios(this.getClientes().getDistritos().get(0).getId()));					
			}		
		} catch (IOException e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
	       
	    return jResponse.success(request, response, wac, model, templateEngine);
	  }	
	
	@RequestMapping(value = "/distritoEvent", method = RequestMethod.POST)
	public @ResponseBody JsonResponse distritooEvent(Model model, HttpServletRequest request, HttpServletResponse response, 
	      @AjaxResponse(View.CLIENTE) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ClientesControllerObject clientes, BindingResult bindingResult) {
		
		this.log.info("INDICADOR DISTRITO EVENT!");
		try {
			this.getClientes().setBarrios(null);
			if ( this.getClientes().getDomicilio().getDistrito() != null) {
				Long idDto = this.getClientes().getDomicilio().getDepartamento().getId();
			  Long id = this.getClientes().getDomicilio().getDistrito().getId();
			  this.getClientes().getDomicilio().setDistrito(this.helperService.getDistritoById(idDto, id));				
			  this.getClientes().setBarrios(this.helperService.getBarrios(this.getClientes().getDomicilio().getDistrito().getId()));					
			}			
		} catch (IOException e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
	    
	    return jResponse.success(request, response, wac, model, templateEngine);
	  }		

	@RequestMapping(value = "/guardarDomicilio", method = RequestMethod.POST)
	public @ResponseBody JsonResponse guardarDomicilio(Model model, HttpServletRequest request, HttpServletResponse response, 
	      @AjaxResponse(View.CLIENTE) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ClientesControllerObject clientes, BindingResult bindingResult) {
		
		this.log.info("GUARDAR DOMICILIO!");
		try {
			// Verifico que se hayan cargado todos los valores
			Long id = null;
			Long idStr = null;
			Long idKey = null;
			
			if ( this.getClientes().getDomicilio().getTipo() == null ) {
				return jResponse.error("Debe informar el tipo de domicilio");
			}
			if ( this.getClientes().getDomicilio().getDepartamento() == null ) {
				return jResponse.error("Debe informar el departamento que pertenece el domicilio");
			}
			if ( this.getClientes().getDomicilio().getDistrito() == null ) {
				return jResponse.error("Debe informar el distrito que pertenece el domicilio");
			}			
            
			id = this.getClientes().getDomicilio().getTipo().getId();		    	
			for (DomicilioDTO obj : this.getClientes().getCliente().getDomicilios()) {
				if ( obj.getTipo().getId().equals(id)) {
					return jResponse.error("Ya existe el tipo de domicilio que se quiere dar de alta");		
				}
			}
			this.getClientes().getDomicilio().setTipo(this.helperService.getTablaRef("TIPDOM", id));
			idStr = this.getClientes().getDomicilio().getDepartamento().getId();
			this.getClientes().getDomicilio().setDepartamento(this.helperService.getDepartamentoById(idStr));
			idKey = this.getClientes().getDomicilio().getDistrito().getId();		    	
			this.getClientes().getDomicilio().setDistrito(this.helperService.getDistritoById(idStr, idKey));
//			id = this.getClientes().getDomicilio().getBarrio().getId();		    	
//			this.getClientes().getDomicilio().setBarrio(this.helperService.getBarrioById(idKey, id));			
			this.getClientes().getCliente().getDomicilios().add(this.getClientes().getDomicilio());
			this.getClientes().setDomicilio(null);
			this.getClientes().setDomicilioOri(null);
			this.getClientes().view().disableAll().enable().cliente();
			
		} catch (IOException e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
	    
	    return jResponse.success(request, response, wac, model, templateEngine);
	  }		

	@RequestMapping(value = "/deleteDomicilio/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse deleteDomicilio(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.CLIENTE) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ClientesControllerObject clientes, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n==============\nELIMINANDO DIRECCION! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			DomicilioDTO obj = this.getClientes().getCliente().getDomicilios().get(index);
			this.log.info("DOMICLIO: {}", obj);
			this.log.info("DOMICLIO ANTES SIZE LISTA: {}", this.getClientes().getCliente().getDomicilios().size());
			if ( obj.getId() != null ) {
				this.getClientes().getCliente().getEliminados().add(obj.getId());
			}
			this.getClientes().getCliente().getDomicilios().remove(obj);
			this.log.info("DOMICLIO DESPUES SIZE LISTA: {}", this.getClientes().getCliente().getDomicilios().size());
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/editarDomicilio/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse editarDomicilio(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.CLIENTE) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ClientesControllerObject clientes, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n============== EDITAR DIRECCION! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			DomicilioDTO obj = this.getClientes().getCliente().getDomicilios().get(index);
			this.log.info("DOMICLIO: {}", obj);
			this.getClientes().setDomicilio(obj);
			this.getClientes().setTipos(this.helperService.getTablaRef("TIPDOM"));
			this.getClientes().setDepartamentos(this.helperService.getDepartamentos());
			this.getClientes().setDistritos(this.helperService.getDistritos(obj.getDepartamento().getId()));	
			this.getClientes().setBarrios(this.helperService.getBarrios(obj.getDistrito().getId()));								
			this.getClientes().view().enable().domicilio();			
			this.getClientes().setDomicilioOri(obj.clone());
			this.getClientes().getCliente().getDomicilios().remove(obj);			
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}

	
	@RequestMapping(value = "/addTelefono", method = RequestMethod.POST)
	public @ResponseBody JsonResponse addTelefono(Model model, HttpServletRequest request, HttpServletResponse response, 
		@AjaxResponse(View.CLIENTE) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ClientesControllerObject clientes, BindingResult bindingResult) {
		this.log.info("clientes - addTelefono!");
		try {
		    this.getClientes().setTelefono(null);
		    this.getClientes().setTelefonoOri(null);
			this.getClientes().setTipos(this.helperService.getTablaRef("TIPTEL"));
			this.getClientes().view().enable().telefono();
		} catch (IOException e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}

		return jResponse.success(request, response, wac, model, templateEngine);
	}	
	
	
	@RequestMapping(value = "/guardarTelefono", method = RequestMethod.POST)
	public @ResponseBody JsonResponse guardarTelefono(Model model, HttpServletRequest request, HttpServletResponse response, 
	      @AjaxResponse(View.CLIENTE) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ClientesControllerObject clientes, BindingResult bindingResult) {
		
		this.log.info("GUARDAR TELEFONO!");
		try {
			// Verifico que se hayan cargado todos los valores
			Long id = null;
			
			if ( this.getClientes().getTelefono().getTipo() == null ) {
				return jResponse.error("Debe informar el tipo de Telefono");
			}
			if ( this.getClientes().getTelefono().getNumero() == null ) {
				return jResponse.error("Debe informar el numero");
			}
            
			id = this.getClientes().getTelefono().getTipo().getId();		    	
			for (TelefonoDTO obj : this.getClientes().getCliente().getTelefonos()) {
				if ( obj.getTipo().getId().equals(id)) {
					return jResponse.error("Ya existe el tipo de telefono que se quiere dar de alta");		
				}
			}
			
			this.getClientes().getTelefono().setTipo(this.helperService.getTablaRef("TIPTEL", id));
			this.getClientes().getCliente().getTelefonos().add(this.getClientes().getTelefono());
			this.getClientes().setTelefono(null);
			this.getClientes().setTelefonoOri(null);
			this.getClientes().view().disableAll().enable().cliente();
			
		} catch (IOException e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
	    
	    return jResponse.success(request, response, wac, model, templateEngine);
	  }		

	@RequestMapping(value = "/deleteTelefono/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse deleteTelefono(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.CLIENTE) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ClientesControllerObject clientes, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n==============\nELIMINANDO TELEFONO! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			TelefonoDTO obj = this.getClientes().getCliente().getTelefonos().get(index);
			this.log.info("Telefono: {}", obj);
			this.getClientes().getCliente().getTelefonos().remove(obj);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/editarTelefono/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse editarTelefono(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.CLIENTE) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ClientesControllerObject clientes, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n============== EDITAR Telefono! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			TelefonoDTO obj = this.getClientes().getCliente().getTelefonos().get(index);
			this.log.info("TELEFONO: {}", obj);
			this.getClientes().setTelefono(obj);
			this.getClientes().setTipos(this.helperService.getTablaRef("TIPTEL"));
			this.getClientes().view().enable().telefono();			
			this.getClientes().setTelefonoOri(obj.clone());
			this.getClientes().getCliente().getTelefonos().remove(obj);			
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}

	@RequestMapping(value = "/guardarCliente", method = RequestMethod.POST)
	public @ResponseBody JsonResponse guardarCliente(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.CLIENTE) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ClientesControllerObject clientes, BindingResult bindingResult) {
		this.log.info("\n==============\nGUARDANDO CLIENTE! \n==============\n");
		try {
			ClienteInfoDTO obj = this.getClientes().getCliente();
			Long idPais = this.getClientes().getPais().getId();
			obj.getPersona().setPais(idPais);
			Long codSex = this.getClientes().getSexo().getId();
			obj.getPersona().setSexo(codSex);
			Long codEst = this.getClientes().getEstadoCivil().getId();
			obj.getPersona().setEstadoCivil(codEst);
			
			if ( obj.getId() == null ) {
				//TODO only before tipopersona module implementation
				obj.getPersona().setTipoPersona(1L);
				this.adminService.crearClienteInfo(obj);
//				this.adminService.crearPersonaInfo(obj);
			} else {
			   this.adminService.actualizarClienteInfo(obj);
			}
			
			this.getClientes().setClientes(this.adminService.obtenerClientes());
			this.getClientes().view().disableAll().enable().lista();
			jResponse.setView(View.CLIENTES);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
			return jResponse.error(e.getMessage());
		}
		
		return jResponse.success(request, response, wac, model, templateEngine);
	}	
	
	@RequestMapping(value = "/editarCliente/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse editarCliente(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.CLIENTES) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ClientesControllerObject clientes, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n============== EDITAR CLIENTE! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			ClienteDTO obj = this.getClientes().getClientes().get(index);
			this.log.info("CLIENTE: {}", obj);
			this.getClientes().setCliente(this.adminService.obtenerCliente(obj.getId()));
			this.getClientes().view().disableAll().enable().cliente();
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}

	@RequestMapping(value = "/eliminarCliente/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse eliminarCliente(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.CLIENTES) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) ClientesControllerObject clientes, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n============== BORRAR CLIENTE! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			ClienteDTO obj = this.getClientes().getClientes().get(index);
			this.log.info("CLIENTE: {}", obj);
			this.adminService.eliminarCliente(obj.getId());
			this.getClientes().setClientes(this.adminService.obtenerClientes());
			this.getClientes().view().disableAll().enable().lista();
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
}	

